package com.design.observer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class Menu extends MenuComponent implements Iterable<MenuComponent>{
	private List<MenuComponent> cs = new ArrayList<>();
	
	@Override
	public String print() {
		return "Menu" + Math.random();
	}

	@Override
	public Iterator<MenuComponent> iterator() {
		return new MenuIterator(cs.iterator());
	}
	
	class MenuIterator implements Iterator<MenuComponent>{
		Stack<Iterator<MenuComponent>> stack = new Stack<>();
		
		public MenuIterator(Iterator<MenuComponent> it) {
			stack.push(it);
		}
		
		@Override
		public boolean hasNext() {
			if(stack.isEmpty()) {
				return false;
			}else {
				Iterator<MenuComponent> peek = stack.peek();
				if(!peek.hasNext()) {
					stack.pop();
					return hasNext();
				}
				return true;
			}
		}

		@Override
		public MenuComponent next() {
			if(hasNext()) {
				Iterator<MenuComponent> peek = stack.peek();
				MenuComponent next = peek.next();
				if(next instanceof Menu) {
					stack.push(((Menu) next).iterator());
				}
				return next;
			}
			return null;
		}
		
	}
}
